# coding:utf-8
class Admin::AreasController < AdminController
	
  respond_to :html, :json
  set_tab :areas, :sub_nav
  before_filter :setup, only: [:index]
  before_filter :determine_level

  def index
    set_tab :terminals
	end

  def new
    case @level
    when 'country'
      @area = @model.new
    when 'province'
      @area = @model.new(:country_id => params[:country_id])
    when 'city'
      @area = @model.new(:province_id => params[:province_id])
    end
  end

  def edit
    @area = @model.find params[:id]
  end

  def create
    @area = @model.new(params[@level])
    render :action => :new unless @area.save
  end

  def update
    @area = @model.find params[:id]
    render :action => :edit unless @area.update_attributes(params[@level])
  end

  def destroy
    @area = @model.find params[:id]
    @area.destroy
  end

  # get province list by country
  def get_provinces_by_country
    options = '<option value>请选择</option>'
    provinces = params[:country_id] == "0" ? Province.all : Province.find_all_by_country_id(params[:country_id])
    provinces.each do |province|  
      options << "<option value=#{province.id}>#{province.name}</option>"  
    end
    render :text => options  
  end

  private

  def determine_level
    @level = ['country', 'province', 'city'].include?(params[:level]) ? params[:level] : 'country'
    set_tab @level
    @model = @level.capitalize.constantize
  end

  def setup
    @ways = ["设备", "区域管理"]
    @left_panel = "admin/areas/area_widget"
  end

end